﻿package com.bestalbum.ui {
	import com.bestalbum.editor.Preset;
	import com.bestalbum.editor.PresetsFactory;
	import com.bestalbum.net.Service;
	import com.bestalbum.ui.controls.BestalbumCursor;
	import com.bestalbum.ui.controls.Pager;
	
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.*;
	import flash.geom.Point;
	import flash.net.*;
	import flash.system.Security;
	import flash.ui.Mouse; 
			import fl.controls.ComboBox;
		import fl.data.DataProvider;
		import flash.utils.ByteArray;
		import flash.display.Shader;
		import flash.display.ShaderData;
		import flash.filters.ShaderFilter; 

	public class Main extends MovieClip {
		
		private var circleMouse:Sprite;
		private var squareMouse:Sprite;
		private var currentMouse:Sprite;
		private var useSquareField:Sprite;
		private var useCircleField:Sprite;
		private var loader:URLLoader;
		private var ldr:Loader;
		protected var so:SharedObject;
		private var book:Book;
		private var imageTarget:ImageTarget;
		private var pager:Pager;
		private var service:Service;
		private var albumTypesComboBox:ComboBox;
		private var albumPresetsComboBox:ComboBox;
		private var shader:Shader;
		private var baCursor:BestalbumCursor;
		private var presetsFactory:PresetsFactory;
		

		
		/* 	
		import fl.controls.ComboBox;
		import fl.data.DataProvider;
		import flash.utils.ByteArray;
		import flash.display.Shader;
		import flash.display.ShaderData;
		import flash.filters.ShaderFilter; 
		*/

		public function Main(){
			Security.allowDomain(Service.SERVICE_DOMAINE);
			if (stage) onAddedToStage();
			else addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			super();
		}
		
		private function onAddedToStage(evt:Event=null):void {
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
			// stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
			// stage.addEventListener(Event.RESIZE, onStageResize);
			initApp();
		}
		
		private function initApp():void {
			// addText("Main::initApp() "+this.scaleX, true); 
			baCursor = new BestalbumCursor();
			currentMouse = new Sprite();
			//baCursor.mouseEnabled = false;
			//baCursor.mouseChildren = false;
			book = new Book();
			addChild(book);
			imageTarget = new ImageTarget();
			imageTarget.addEventListener(MouseEvent.ROLL_OVER, useCustomMouse);
			imageTarget.addEventListener(MouseEvent.ROLL_OUT, restoreMouse);
			addChild(imageTarget);
			pager = new Pager(this, book.x + 70, book.y + book.height - 60, 830, 20, 16);
			addChild(pager);
			
			presetsFactory = PresetsFactory.getInstance();		
			service = new Service(this);	
			service.addEventListener(Service.EVENT_EXCHANGE, onExchange);
			service.dataExchange(Service.ACTION_INIT_INTERFACE);
		}
		
		private function useCustomMouse(mouseEvent:MouseEvent):void{
			Mouse.hide();
			addChild(baCursor); // or another
			currentMouse = baCursor;
		}
		
		private function restoreMouse(mouseEvent:MouseEvent):void{
			// if((mouseEvent.target as Sprite) == useSquareField) removeChild(squareMouse);
			// else removeChild(circleMouse);
			removeChild(baCursor);
			currentMouse = new Sprite();
			Mouse.show();
		}
		
		private function mouseMoveHandler(mouseEvent:MouseEvent):void{
			var point:Point = new Point(mouseEvent.stageX, mouseEvent.stageY);
			var mypoint:Point = this.globalToLocal(point);
			currentMouse.x = mypoint.x;
			currentMouse.y = mypoint.y;
			mouseEvent.updateAfterEvent();
		}
		
		private function mouseLeaveHandler(evt:Event):void{
			trace("mouseLeaveHandler");
		}
		
		private function onStageResize(evt:Event):void{
			addText("Main::onStageResize() "+evt.target.scaleX, true);
		}

		public function onExchange(event:DataEvent){
			var _xml:XML = new XML(event.data);
			// addText("Main::onExchange() _xml="+_xml, true);
			addText("Main::onExchange() action="+_xml.action, true);
			switch (_xml.action+"") {
				case Service.ACTION_INIT_INTERFACE:
					initInterface(_xml);
				break;
				case Service.ACTION_GET_CLIENT_PROFILE:
					addText("Main::onExchange() YO!", true);
				break;
			}
			service.removeEventListener(Service.EVENT_EXCHANGE, onExchange);
		}
		
		public function onLoadComplete(event:Event):void {
			addText("Main::onLoadComplete()", true); 
		    shader = new Shader(loader.data); 
		    var sd:ShaderData = shader.data;
		    sd.intensity = 0.2;
		    shader.data = sd;
		    var sepiaFilter:ShaderFilter = new ShaderFilter(shader); 
            imageTarget.filters = [sepiaFilter]; 

		}
		
		private function initInterface(_xml:XML){
			
			// addText("Main::initInterface() albumTypes="+_xml.albumTypes, true);
			var filters:XMLList = _xml.albumTypes.albumType.albumPresets.albumPreset.presetFilters.presetFilter;
			// addText("Main::initInterface() filters="+filters, true);
			presetsFactory.prepareFilters(filters);

			var dp:Array = new Array();
			var selectedType:int = 0;
			try{
				var types:XMLList = _xml.albumTypes.albumType;
				for (var i:int = 0; i < types.length(); i++){ 
					dp.push({label:types[i].@name, data:types[i]});
					if(types[i].@is_default == "1") selectedType = i;
				}
				albumTypesComboBox = new ComboBox();
				albumTypesComboBox.dataProvider = new DataProvider(dp);
				albumTypesComboBox.move(20, 430);
				albumTypesComboBox.addEventListener(Event.OPEN, albumTypesOpenHandler);
				albumTypesComboBox.addEventListener(Event.CLOSE, albumTypesCloseHandler);
				albumTypesComboBox.addEventListener(Event.CHANGE,  albumTypesChangeHandler); 
				albumTypesComboBox.selectedIndex = selectedType;
				addChild(albumTypesComboBox);

				albumPresetsComboBox = new ComboBox();
				albumPresetsComboBox.move(150, 430);
				albumPresetsComboBox.addEventListener(Event.OPEN, albumPresetsOpenHandler);
				albumPresetsComboBox.addEventListener(Event.CLOSE, albumPresetsCloseHandler);
				albumPresetsComboBox.addEventListener(Event.CHANGE,  albumPresetsChangeHandler); 
				addChild(albumPresetsComboBox);
				setPresetsComboData();
				
			} catch (er:Error){
				addText("Main::initInterface() ERROR "+er, true);
			}
		}
		
		private function setPresetsComboData():void{
				var dp:Array = [];
				var selectedPreset:int = 0;
				var presets:XMLList = albumTypesComboBox.selectedItem.data.albumPresets.albumPreset;
				for (var i:int = 0; i < presets.length(); i++){ 
					dp.push({label:presets[i].@name, data:presets[i]});
					if(presets[i].@is_default == "1") selectedPreset = i;
				}
				albumPresetsComboBox.dataProvider = new DataProvider(dp);
				albumPresetsComboBox.selectedIndex = selectedPreset;
		}
		
		public function albumTypesOpenHandler(event:Event):void {
			addText("Main::albumTypesOpenHandler()", true);
		}
		
		public function albumTypesCloseHandler(event:Event):void {
			addText("Main::albumTypesCloseHandler()", true);
		}
		
		public function albumTypesChangeHandler(event:Event):void {
			addText("Main::albumTypesChangeHandler()", false);
			setPresetsComboData();
		}
		
		public function albumPresetsOpenHandler(event:Event):void {
			addText("Main::albumPresetsOpenHandler()", true);
		}
		
		public function albumPresetsCloseHandler(event:Event):void {
			addText("Main::albumPresetsCloseHandler()", true);
		}
		
		public function albumPresetsChangeHandler(event:Event):void {
			addText("Main::albumPresetsChangeHandler() ", false);
			var filters:XMLList = albumPresetsComboBox.selectedItem.data.presetFilters.presetFilter;
			presetsFactory.applyPreset(imageTarget, filters);
		}
		
		public function addText(txt:String, append:Boolean){
			book.addText(txt, append);
		}
		
		public function onPresetSelected(event:Event):void {
			trace("onPresetSelected :: event="+event);
			trace("onPresetSelected :: event.target="+event.target);
			var preset:Preset = Preset(event.target);
			trace("preset=" + preset.preset);
		}
		private function mouseDownHandler(mouseEvent:MouseEvent):void{
			trace("mouseDownHandler");
		}

		
		
		private function mouseOutHandler(mouseEvent:MouseEvent):void{
			trace("mouseOutHandler");
		}
		private function mouseUpHandler(mouseEvent:MouseEvent):void{
			trace("mouseUpHandler");
		}
		private function mouseWheelHandler(mouseEvent:MouseEvent):void{
			trace("mouseWheelHandler");
		}
		private function mouseOverHandler(mouseEvent:MouseEvent):void{
			trace("mouseOverHandler");
		}
		private function doubleClickHandler(mouseEvent:MouseEvent):void{
			trace("doubleClickHandler");
		}
	
		public function networkProject(){
			var request:URLRequest = new URLRequest("http://beta.bestalbum.ru/crossdomain.xml");
			loader = new URLLoader(request);
			loader.addEventListener(Event.ACTIVATE, activatedListener);
			loader.addEventListener(Event.COMPLETE, completeListener);
			loader.addEventListener(ProgressEvent.PROGRESS, progressListener);
		}
		private function activatedListener(event:Event):void{
			trace(" activated " + loader.bytesLoaded + 
			" but nothing loaded yet ");
		}
		private function completeListener(event:Event):void{
			trace(" all done loading " + loader.data + 
			" and here's the xml file we loaded ");
		}
		private function progressListener(event:Event):void{
			trace(" we're in progress, we've loaded " + loader.bytesLoaded + 
			" out of " + loader.bytesTotal + " bytes ");
		}
		
		public function loaderDemo(){
			try{			
				ldr = new Loader();
				ldr.load(new URLRequest("http://beta.bestalbum.ru/images/face.PNG"));
				ldr.contentLoaderInfo.addEventListener(Event.COMPLETE,contentComplete);
				addChild(ldr);
			} catch(error:Error){
				trace("Main::loaderDemo():: ERROR" + error.name);
				trace("Main::loaderDemo():: ERROR" + error.message);
			}
		}
		private function contentComplete(event:Event):void{
			trace(ldr.content);
		}
		
		public function overflowTest(){
			so = SharedObject.getLocal("storage");
			//request 1 MB up front
			if (so.flush(1024 * 1024) == SharedObjectFlushStatus.PENDING){
				so.addEventListener(NetStatusEvent.NET_STATUS, onUserAction);
				trace("User approval pending...");
			}
		}
		public function onUserAction(event:NetStatusEvent):void{
			so.removeEventListener(NetStatusEvent.NET_STATUS, onUserAction);
			switch (event.info.code){
				case "SharedObject.Flush.Success":
					trace("Accepted");
				break;
				case "SharedObject.Flush.Failed":
					trace("Denied");
					//do error recovery
				break;
			}
		}
	}
}